package com.wv.api.service.basic.impl;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.wv.api.mapper.basic.BasicAreaCodeDao;
import com.wv.api.service.basic.IBasicAreaCodeService;
import com.wv.common.result.HttpCodeEnum;
import com.wv.common.result.Result;
import com.wv.model.basic.BasicAreaCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class BasicAreaCodeServiceImpl implements IBasicAreaCodeService {

    @Autowired
    private BasicAreaCodeDao basicAreaCodeDao;

    @Override
    public Result getAll() {
        List<BasicAreaCode> basicAreaCodes = basicAreaCodeDao.selectList(null);
        return Result.ok(basicAreaCodes);
    }

    @Override
    public Result getTreeData() {
        List<BasicAreaCode> basicAreaCodes = basicAreaCodeDao.selectList(null);
        List<BasicAreaCode> treeData = basicAreaCodes.stream().filter(item -> item.getParentCode().equals("0"))
                .map(item -> item.setChildren(getChild(item.getCode(), basicAreaCodes)))
                .sorted(Comparator.comparing(area -> (area.getLevel() == null ? 0 : area.getLevel())))
                .collect(Collectors.toList());
        return Result.ok(treeData);
    }

    @Override
    public SaResult addArea(BasicAreaCode basicAreaCode) {
        //        生成id
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        basicAreaCode.setId(snowflake.nextIdStr());
        int i = basicAreaCodeDao.insert(basicAreaCode);
        return i > 0 ? SaResult.ok() : SaResult.error(HttpCodeEnum.ADD_ERROR.getMsg());
    }

    @Override
    public SaResult updateArea(BasicAreaCode basicAreaCode) {
        int i = basicAreaCodeDao.updateById(basicAreaCode);
        return i > 0 ? SaResult.ok() : SaResult.error(HttpCodeEnum.UPDATE_ERROR.getMsg());
    }

    @Override
    public SaResult deleteArea(String id) {
        int i = basicAreaCodeDao.deleteById(id);
        return i > 0 ? SaResult.ok() : SaResult.error(HttpCodeEnum.DElETE_ERROR.getMsg());
    }

    public List<BasicAreaCode> getChild(String code,List<BasicAreaCode> basicAreaCodes){
        return basicAreaCodes.stream().filter(item -> Objects.equals(code,item.getParentCode()))
                .map(item -> item.setChildren(getChild(item.getCode(), basicAreaCodes)))
                .sorted(Comparator.comparing(area -> (area.getLevel() == null ? 0 : area.getLevel())))
                .collect(Collectors.toList());
    }
}
